import os
import pathlib
import re
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext

class CommentSplitterApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("评价文本拆分工具")
        self.geometry("800x650")  # 增大高度
        self.minsize(700, 600)
        
        # 设置样式
        self.style = ttk.Style()
        self.style.configure("TButton", font=("微软雅黑", 10))
        self.style.configure("TLabel", font=("微软雅黑", 10))
        self.style.configure("Header.TLabel", font=("微软雅黑", 12, "bold"))
        self.style.configure("TCheckbutton", font=("微软雅黑", 10))
        
        # 初始化变量
        self.comment_path = tk.StringVar()
        self.output_path = tk.StringVar()
        self.filter_text = tk.StringVar()
        self.comments = []
        self.filtered_comments = []
        
        self.init_ui()
    
    def init_ui(self):
        """初始化用户界面，重新调整布局"""
        # 主框架，设置统一的内边距
        main_frame = ttk.Frame(self, padding=(20, 20, 20, 10))
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题，单独一行
        ttk.Label(
            main_frame, 
            text="评价文本拆分工具", 
            style="Header.TLabel"
        ).grid(row=0, column=0, columnspan=3, pady=(0, 20), sticky=tk.W)
        
        # 输入区域 - 评价文本文件选择
        ttk.Label(main_frame, text="评价文本文件:").grid(row=1, column=0, sticky=tk.W, pady=(0,5))
        ttk.Entry(main_frame, textvariable=self.comment_path, width=40).grid(row=1, column=1, pady=(0,5), padx=5, sticky=tk.EW)
        ttk.Button(
            main_frame, 
            text="浏览...", 
            command=self.select_comment_file
        ).grid(row=1, column=2, pady=(0,5), padx=5, sticky=tk.W)
        
        # 输入区域 - 输出目录选择
        ttk.Label(main_frame, text="输出目录:").grid(row=2, column=0, sticky=tk.W, pady=(0,5))
        ttk.Entry(main_frame, textvariable=self.output_path, width=40).grid(row=2, column=1, pady=(0,5), padx=5, sticky=tk.EW)
        ttk.Button(
            main_frame, 
            text="浏览...", 
            command=self.select_output_path
        ).grid(row=2, column=2, pady=(0,5), padx=5, sticky=tk.W)
        
        # 让输入区域的列自适应
        main_frame.grid_columnconfigure(1, weight=1)
        
        # 过滤设置区域，单独一行
        filter_frame = ttk.LabelFrame(main_frame, text="过滤设置", padding=10)
        filter_frame.grid(row=3, column=0, columnspan=3, pady=15, sticky=tk.EW)
        
        ttk.Label(filter_frame, text="包含以下内容的评价:").grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Entry(filter_frame, textvariable=self.filter_text, width=30).grid(row=0, column=1, pady=5, padx=5, sticky=tk.EW)
        ttk.Button(
            filter_frame, 
            text="应用过滤", 
            command=self.apply_filter
        ).grid(row=0, column=2, pady=5, padx=5, sticky=tk.W)
        
        # 过滤选项，单独一行
        filter_options_frame = ttk.Frame(filter_frame)
        filter_options_frame.grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=5)
        
        self.exact_match = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            filter_options_frame, 
            text="精确匹配", 
            variable=self.exact_match
        ).pack(side=tk.LEFT, padx=10)
        
        self.case_sensitive = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            filter_options_frame, 
            text="区分大小写", 
            variable=self.case_sensitive
        ).pack(side=tk.LEFT, padx=10)
        
        # 让过滤区域的列自适应
        filter_frame.grid_columnconfigure(1, weight=1)
        
        # 评价预览区域，单独一行，设置更大高度
        preview_frame = ttk.LabelFrame(main_frame, text="评价预览", padding=10)
        preview_frame.grid(row=4, column=0, columnspan=3, pady=15, sticky=tk.EW)
        
        self.preview_text = scrolledtext.ScrolledText(
            preview_frame, 
            wrap=tk.WORD, 
            height=12  # 增加预览框高度
        )
        self.preview_text.pack(fill=tk.BOTH, expand=True)
        self.preview_text.config(state=tk.DISABLED)
        
        # 状态标签，单独一行
        self.status_label = ttk.Label(main_frame, text="就绪", foreground="blue")
        self.status_label.grid(row=5, column=0, columnspan=3, sticky=tk.W, pady=(0,10))
        
        # 操作按钮区域，单独一行，右对齐拆分按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=6, column=0, columnspan=3, sticky=tk.EW)
        
        ttk.Button(
            btn_frame, 
            text="加载评价", 
            command=self.load_comments
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="拆分评价", 
            command=self.split_comments
        ).pack(side=tk.RIGHT, padx=5)
        
        # 让按钮区域的列自适应
        btn_frame.grid_columnconfigure(0, weight=1)
    
    def select_comment_file(self):
        """选择评价文本文件"""
        default_dir = os.getcwd()
        file_path = filedialog.askopenfilename(
            title="选择评价文本文件",
            initialdir=default_dir,
            filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
        )
        if file_path:
            self.comment_path.set(file_path)
    
    def select_output_path(self):
        """选择输出目录"""
        default_dir = os.path.join(os.path.expanduser("~"), "Desktop")
        dir_path = filedialog.askdirectory(
            title="选择输出目录",
            initialdir=default_dir
        )
        if dir_path:
            self.output_path.set(dir_path)
    
    def load_comments(self):
        """加载评价文本文件"""
        file_path = self.comment_path.get()
        if not file_path or not os.path.exists(file_path):
            messagebox.showerror("错误", "请选择有效的评价文本文件")
            return
        
        try:
            with open(file_path, mode='r', encoding='utf-8') as file:
                self.comments = [line.strip() for line in file.readlines() if line.strip()]
            
            self.filtered_comments = self.comments.copy()
            self.update_preview()
            self.status_label.config(text=f"已加载 {len(self.comments)} 条评价")
            messagebox.showinfo("成功", f"已加载 {len(self.comments)} 条评价")
        except Exception as e:
            messagebox.showerror("错误", f"加载文件失败: {str(e)}")
            self.status_label.config(text="加载失败")
    
    def apply_filter(self):
        """应用过滤条件"""
        if not self.comments:
            messagebox.showwarning("警告", "请先加载评价文件")
            return
        
        filter_str = self.filter_text.get()
        if not filter_str:
            self.filtered_comments = self.comments.copy()
            self.update_preview()
            self.status_label.config(text="已清除过滤条件")
            return
        
        self.filtered_comments = []
        for comment in self.comments:
            if self.match_filter(comment, filter_str):
                self.filtered_comments.append(comment)
        
        self.update_preview()
        self.status_label.config(
            text=f"已过滤出 {len(self.filtered_comments)} 条评价 (共 {len(self.comments)} 条)"
        )
    
    def match_filter(self, comment, filter_str):
        """检查评价是否符合过滤条件"""
        if not self.case_sensitive.get():
            comment = comment.lower()
            filter_str = filter_str.lower()
        
        if self.exact_match.get():
            return filter_str in comment
        else:
            try:
                return re.search(filter_str, comment) is not None
            except re.error:
                return filter_str in comment
    
    def update_preview(self):
        """更新评价预览"""
        self.preview_text.config(state=tk.NORMAL)
        self.preview_text.delete(1.0, tk.END)
        
        display_count = min(20, len(self.filtered_comments))  # 最多显示20条
        for i, comment in enumerate(self.filtered_comments[:display_count], 1):
            self.preview_text.insert(tk.END, f"{i}. {comment}\n\n")
        
        if len(self.filtered_comments) > display_count:
            self.preview_text.insert(tk.END, f"... 还有 {len(self.filtered_comments) - display_count} 条未显示...\n")
        
        self.preview_text.config(state=tk.DISABLED)
    
    def split_comments(self):
        """拆分评价并保存"""
        output_dir = self.output_path.get()
        if not output_dir:
            messagebox.showerror("错误", "请选择输出目录")
            return
        
        if not self.filtered_comments:
            messagebox.showerror("错误", "无有效评价可拆分，请先加载并过滤")
            return
        
        try:
            main_output_path = pathlib.Path(output_dir).joinpath("评价文本集合")
            main_output_path.mkdir(parents=True, exist_ok=True)
            
            self.preview_text.config(state=tk.NORMAL)
            self.preview_text.delete(1.0, tk.END)
            
            for idx, comment in enumerate(self.filtered_comments, 1):
                comment_dir = main_output_path.joinpath(f"评价{idx}")
                comment_dir.mkdir(parents=True, exist_ok=True)
                
                with open(comment_dir.joinpath("comment.txt"), "w", encoding="utf-8") as f:
                    f.write(comment)
                
                self.preview_text.insert(tk.END, f"已保存: 评价{idx}\n{comment[:50]}...\n\n")
                self.preview_text.see(tk.END)
                self.update_idletasks()
                
                self.status_label.config(text=f"正在处理: {idx}/{len(self.filtered_comments)}")
            
            self.preview_text.config(state=tk.DISABLED)
            self.status_label.config(text=f"处理完成: 共保存 {len(self.filtered_comments)} 条评价")
            messagebox.showinfo(
                "成功", 
                f"拆分完成！\n保存路径: {main_output_path}\n共保存 {len(self.filtered_comments)} 条评价"
            )
            
        except Exception as e:
            messagebox.showerror("错误", f"保存失败: {str(e)}")
            self.status_label.config(text="处理失败")

if __name__ == "__main__":
    app = CommentSplitterApp()
    app.mainloop()